#define WIN32_LEAN_AND_MEAN

#include <winsock2.h>
#include <Ws2tcpip.h>
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>

#define DEFAULT_BUFLEN 512
#define DEFAULT_HOSTIP "127.0.0.1"
#define DEFAULT_HOSTPORT 40400

  
int __cdecl main(int argc, char *argv[]) 
{
    //----------------------
    // Declare and initialize variables.
    WSADATA wsaData;
    int iResult;

    SOCKET ConnectSocket;
    struct sockaddr_in clientService; 

    char recvbuf[DEFAULT_BUFLEN];
    int recvbuflen;
    
    // Initialise
    ConnectSocket = INVALID_SOCKET;
    recvbuflen = DEFAULT_BUFLEN;

    char hostip[132];
    int hostport;
    if (argc>1) { strcpy(hostip,argv[1]); } else { strcpy(hostip,DEFAULT_HOSTIP); }
    if (argc>2) { hostport=atoi(argv[2]); } else { hostport=DEFAULT_HOSTPORT; }
    
    //----------------------
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != NO_ERROR) {
      printf("WSAStartup failed: %d\n", iResult);
      return 1;
    }

    //----------------------
    // Create a SOCKET for connecting to server
    ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ConnectSocket == INVALID_SOCKET) {
        printf("Error at socket(): %ld\n", WSAGetLastError() );
        WSACleanup();
        return 1;
    }

    //----------------------
    // The sockaddr_in structure specifies the address family,
    // IP address, and port of the server to be connected to.
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr( hostip );
    clientService.sin_port = htons( hostport );

    //----------------------
    // Connect to server.
    iResult = connect( ConnectSocket, (SOCKADDR*) &clientService, sizeof(clientService) );
    if ( iResult == SOCKET_ERROR) {
        closesocket (ConnectSocket);
        printf("Unable to connect to server: %ld\n", WSAGetLastError());
        WSACleanup();
        return 1;
    }

    // Receive until the peer closes the connection
    do {

        iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
        if ( iResult > 0 )
            {
              recvbuf[iResult]='\0';
              printf("%s\n======================================================================\n", recvbuf);
            }
        else if ( iResult == 0 )
            printf("Connection closed\n");
        else
            printf("recv failed: %d\n", WSAGetLastError());

    } while( iResult > 0 );

    // cleanup
    closesocket(ConnectSocket);
    WSACleanup();
    return 0;
}


 
